package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理器
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /*
    针对不同的异常进行处理
    抓取到指定异常 对指定异常进行处理
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.warn("查看异常信息" + e.getMessage());

        if (e.getMessage().contains("Duplicate entry")) {
            String n = e.getMessage().split(" ")[2];
            //split按照空格截取Duplicate entry "列名" for key "字段"
            return R.error("字段" + n + "重复");
        } else if (e.getMessage().contains("cannot be null")) {
            String n = e.getMessage().split(" ")[1];
            //split按照空格截取Column "列名" cannot be null
            return R.error("字段" + n + "不能为null");
        } else {
            return R.error("未知问题...........");
        }
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException e) {
        log.warn("当前异常信息" + e.getMessage());
        return R.error(e.getMessage());
    }

}
